import pandas as pd
from datetime import datetime, timedelta, date,timezone
import os
from pymongo import MongoClient 
import numpy as np



# 管理网数据库数据服务器:
# user:root
# IP: 10.0.0.152
# 密码: ENINt@0@4


# pd.set_option('display.max_rows', None)
# pd.set_option('display.max_columns', None)



class MongoAccess():
    def __init__(self, localtz=None, SVR_MONGO_URI=None, SVR_DB_NAME=None):
        # 加载配置文件
        config_path = os.path.join(os.path.dirname(__file__), "config.json")
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                config = json.load(f)
            mango_config = config.get("getdatafrommango", {})
            
            # 如果参数为None，则从配置文件中读取
            if localtz is None:
                localtz = mango_config.get("localtz", "Asia/Shanghai")
            if SVR_MONGO_URI is None:
                SVR_MONGO_URI = mango_config.get("SVR_MONGO_URI", "mongodb://eCDUsvr:eCDUsvr2020@10.0.0.233:27017")
            if SVR_DB_NAME is None:
                SVR_DB_NAME = mango_config.get("SVR_DB_NAME", "eCDU")
        except Exception as e:
            print(f"无法加载配置文件，使用默认值: {e}")
            # 使用默认值
            if localtz is None:
                localtz = "Asia/Shanghai"
            if SVR_MONGO_URI is None:
                SVR_MONGO_URI = "mongodb://eCDUsvr:eCDUsvr2020@10.0.0.233:27017"
            if SVR_DB_NAME is None:
                SVR_DB_NAME = "eCDU"
        self.client = MongoClient(SVR_MONGO_URI)
        self.localtz = localtz
        self.SVR_MONGO_URI = SVR_MONGO_URI
        self.SVR_DB_NAME = SVR_DB_NAME

    def _tz_convert(self, start, end):
        if start.tz is None:
            start = start.tz_localize(self.localtz)
                
        if start.tz != 'UTC':
            start = start.astimezone('UTC')

        if end.tz is None:
            end = end.tz_localize(self.localtz)
        
        if end.tz != 'UTC':
            end = end.astimezone('UTC')
        return start, end

    def loadDataFrame(self, dbname, collection, find, incId=False, sort=None):
        db = self.client[dbname]
        coll = db[collection]
        if incId:
            cursor = coll.find(find)
        else:
            cursor = coll.find(find,{"_id":incId})
        if sort is not None:
            cursor = cursor.sort(sort)
        df =  pd.DataFrame(list(cursor))
        return df

        
    def __delete(self):
        pass
        # self.dbcSvr.disconnect()
    
    def readLIMS(self, startTime, endTime):
        LIMSData = self.loadDataFrame(self.SVR_DB_NAME, 'd_LIMS',
                                      {"insertODSTime": {"$gt": startTime, "$lte": endTime}})
        if LIMSData is not None and not LIMSData.empty:
            LIMSData['samplingTime'] = LIMSData.set_index('samplingTime').index.tz_localize(
                timezone.utc).tz_convert(self.localtz)
            LIMSData['insertODSTime'] = LIMSData.set_index('insertODSTime').index.tz_localize(
                timezone.utc).tz_convert(self.localtz)
        return LIMSData

           
if __name__ == "__main__":
    # 从配置文件读取参数
    config_path = os.path.join(os.path.dirname(__file__), "config.json")
    try:
        with open(config_path, 'r', encoding='utf-8') as f:
            config = json.load(f)
        mango_config = config.get("getdatafrommango", {})
        
        endTime = datetime.now()
        endTime = pd.to_datetime(endTime)
        delta = timedelta(hours=mango_config.get("time_span_hours", 0.5))
        startTime = endTime-delta
        
        # 直接创建MongoAccess实例，内部会从配置读取参数
        cli = MongoAccess()
    except Exception as e:
        print(f"配置读取失败，使用默认值: {e}")
        cli = MongoAccess()
    Data = cli.readLIMS(startTime, endTime)
    print(Data)
    
    
